package com.campusbackend.controller;

import com.campusbackend.entity.AdminUsers;
import com.campusbackend.entity.Result;
import com.campusbackend.entity.vo.AdminLoginVO;
import com.campusbackend.entity.vo.AdminLoginRequestVO;
import com.campusbackend.service.AdminUsersService;
import com.campusbackend.utils.JwtUtil;
import com.campusbackend.utils.ResultUtil;
import com.campusbackend.utils.ThreadLocalUtil;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 管理员用户表 前端控制器
 * </p>
 *
 * @author yezi
 * @since 2025-07-24
 */
@Slf4j
@RestController
@Validated
@RequestMapping("/adminUser")
public class AdminUsersController {

    @Autowired
    private AdminUsersService adminUsersService;
    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 管理员登录
     * @param loginVO 登录信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<AdminLoginVO> login(@Valid @RequestBody AdminLoginRequestVO loginVO) {
        log.info("管理员登录请求 - username: {}", loginVO.getUsername());

        try {
            // 根据用户名查找管理员
            AdminUsers admin = adminUsersService.findByUsername(loginVO.getUsername());

            // 判断账号是否存在
            if (admin == null) {
                return ResultUtil.fail("该用户不存在！");
            }

            // 检查账号状态
            if (admin.getStatus() == 0) {
                return ResultUtil.fail("账号已被禁用！");
            }

            // 验证密码
            if (!passwordEncoder.matches(loginVO.getPassword(), admin.getPassword())) {
                return ResultUtil.fail("密码错误！");
            }

            // 生成JWT token
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", admin.getId());
            claims.put("username", admin.getUsername());
            claims.put("userType", "admin");

            String token = JwtUtil.genToken(claims, 1000L * 60 * 60); // 1小时过期

            // 存储到Redis
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 1, TimeUnit.HOURS);

            log.info("管理员登录成功 - username: {}, realName: {}", admin.getUsername(), admin.getRealName());

            // 创建返回对象
            AdminLoginVO adminLoginVO = new AdminLoginVO(token, 200);

            return ResultUtil.success(adminLoginVO);

        } catch (Exception e) {
            log.error("管理员登录异常", e);
            return ResultUtil.fail("登录过程中发生错误，请稍后重试");
        }
    }

    /**
     * 获取管理员个人信息
     * @return 管理员信息
     */
    @GetMapping("/getAdminInfo")
    public Result<AdminUsers> getAdminInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        AdminUsers admin = adminUsersService.findByUsername(username);
        if (admin != null) {
            // 不返回密码
            admin.setPassword(null);
            return ResultUtil.success(admin);
        }
        return ResultUtil.fail("用户不存在");
    }
}
